<template>
    <div class="edu-page-warp">
        <el-card shadow="never">
            <edu-form :model="teachForm" :rules="rules" ref="teachForm" label-width="150px">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item :label="$t('label.schoolTerm')" class="is-required">
                            <CalendarSelect
                                v-model="teachForm.calendarId"
                                :disabled="ifEdit || ifDisabled"
                            ></CalendarSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('问卷主题名')" prop="managementName">
                            <el-input
                                maxlength="128"
                                :disabled="ifEdit || ifDisabled"
                                v-model="teachForm.managementName"
                                :placeholder="$t('请输入')"
                            ></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item :label="$t('评教评价模板')" prop="templateMainId">
                            <el-select
                                v-model="teachForm.templateMainId"
                                :disabled="ifDisabled"
                                style="width: 100%;"
                            >
                                <el-option
                                    v-for="item in templateList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item :label="$t('评教权限开始时间')" prop="startTime">
                            <el-date-picker
                                style="width: 100%;"
                                v-model="teachForm.startTime"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                format="yyyy-MM-dd HH:mm:ss"
                                placeholder="选择日期时间"
                                :picker-options="pickerOptions1"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item :label="$t('评教权限结束时间')" prop="endTime">
                            <el-date-picker
                                style="width: 100%;"
                                v-model="teachForm.endTime"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                format="yyyy-MM-dd HH:mm:ss"
                                placeholder="选择日期时间"
                                :picker-options="pickerOptions2"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('评教率')" prop="evaluationRate">
                            <el-input
                                maxlength="32"
                                v-model="teachForm.evaluationRate"
                                :placeholder="$t('请输入')"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="16">
                        <el-form-item :label="$t('评教问卷前言')" prop="introduction">
                            <el-input
                                type="textarea"
                                :rows="7"
                                maxlength="500"
                                v-model="teachForm.introduction"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </edu-form>
            <el-row :gutter="20" style="text-align: right;">
                <el-button @click="cancel()">{{ $t('message.cancel') }}</el-button>
                <el-button @click="save">{{ $t('message.save') }}</el-button>
                <el-button :disabled="!teachForm.templateMainId" @click="addPreviewClick">
                    {{ $t('预览') }}
                </el-button>
                <el-button type="primary" @click="nextStep">{{ $t('下一步') }}</el-button>
            </el-row>
        </el-card>
    </div>
</template>
<script>
import courseEvaluationApi from 'common/src/api/teachingEvaluation/courseEvaluation'
import SchoolCalendarApi from 'common/src/api/calendars'
import templateApi from 'common/src/api/teachingEvaluation/template'
export default {
    name: 'AddQuestionaireOfTeach',
    props: {
        ifEdit: {
            type: Boolean,
            default: false
        },
        ifPrev: {
            type: Boolean,
            default: false
        }
    },
    data() {
        let validateEvaluationRate = (rule, value, callback) => {
            let reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/
            if (value === '') {
                return callback(new Error('请输入0-1之间的数字，最多保留两位小数'))
            } else if (!reg.test(value)) {
                return callback(new Error('请输入0-1之间的数字，最多保留两位小数'))
            } else if (value <= 0) {
                return callback(new Error('请输入0-1之间的数字，最多保留两位小数'))
            } else if (value > 1) {
                return callback(new Error('请输入0-1之间的数字，最多保留两位小数'))
            }
            return callback()
        }
        return {
            routeParams: {},
            ifDisabled: false,
            teachForm: {
                managementId: '',
                managementName: '',
                templateMainId: '',
                calendarId: '',
                startTime: '',
                endTime: '',
                evaluationRate: '',
                introduction: ''
            },
            currentCalendarId: '',
            templateList: [],
            rules: {
                managementName: [{ required: true, message: '请填写问卷主题名', trigger: 'blur' }],
                templateMainId: [
                    { required: true, message: '请选择评教评价模板', trigger: 'change' }
                ],
                startTime: [
                    { required: true, message: '请选择评教权限开始时间', trigger: 'change' }
                ],
                endTime: [{ required: true, message: '请选择评教权限结束时间', trigger: 'change' }],
                introduction: [{ required: true, message: '请填写评教问卷前言', trigger: 'blur' }],
                evaluationRate: [
                    { required: true, message: '请填写评教率', trigger: 'blur' },
                    { validator: validateEvaluationRate }
                ]
            },
            pickerOptions1: {
                disabledDate: time => {
                    if (this.teachForm.endTime != null) {
                        return (
                            new Date(time).getTime() + 86400 >
                            new Date(this.teachForm.endTime).getTime()
                        )
                    } else {
                        return false
                    }
                }
            },
            pickerOptions2: {
                disabledDate: time => {
                    return (
                        new Date(time).getTime() <
                        new Date(this.teachForm.startTime).getTime() + 86400
                    )
                }
            }
        }
    },
    created() {
        if (this.$route.query.ifWithdraw === 'true' || this.$route.query.ifWithdraw === true) {
            this.ifDisabled = true
        }
        if (this.$route.query.managementId) {
            const param = {
                managementId: this.$route.query.managementId
            }
            courseEvaluationApi.getStudentEvaDetail(param).then(res => {
                if (res.code == 200) {
                    this.teachForm = res.data
                }
            })
        }
    },
    mounted() {
        templateApi
            .getTemplateListByType({
                type: 1
            })
            .then(res => {
                if (res.data) {
                    this.templateList = res.data
                }
            })
        this.getCurrentTermCalendar().then(resp => {
            this.currentCalendarId = resp.data.schoolCalendar.id
        })
    },
    methods: {
        // 获取当前学年学期
        async getCurrentTermCalendar() {
            return await SchoolCalendarApi.currentTermCalendar()
        },
        // 新增预览
        addPreviewClick() {
            this.$emit('goToPreview', this.teachForm)
        },
        // 下一步
        nextStep() {
            this.$refs.teachForm.validate(valid => {
                if (valid) {
                    if (!this.ifEdit && !this.ifPrev) {
                        courseEvaluationApi.addStudentEva(this.teachForm).then(res => {
                            this.$router.push({
                                query: {
                                    managementId: res.data.managementId,
                                    calendarId: this.teachForm.calendarId,
                                    ifWithdraw: this.$route.query.ifWithdraw ? this.$route.query.ifWithdraw : this.routeParams.ifWithdraw
                                }
                            })
                            if (res.code === 200) {
                                this.$message.success('保存成功')
                                this.$emit('goToAddNext')
                            }
                        })
                    } else {
                        courseEvaluationApi.updateStudentEva(this.teachForm).then(res => {
                            this.$router.push({
                                query: {
                                    managementId: res.data.managementId,
                                    calendarId: this.teachForm.calendarId,
                                    ifWithdraw: this.$route.query.ifWithdraw ? this.$route.query.ifWithdraw : this.routeParams.ifWithdraw
                                }
                            })
                            if (res.code === 200) {
                                this.$message.success('保存成功')
                                this.$emit('goToAddNext')
                            }
                        })
                    }
                }
            })
        },
        // 取消
        cancel() {
            this.$emit('onlyGoBack')
        },
        // 新增/编辑提交
        save() {
            this.$refs.teachForm.validate(valid => {
                if (valid) {
                    if (!this.ifEdit && !this.ifPrev) {
                        courseEvaluationApi.addStudentEva(this.teachForm).then(res => {
                            if (res.code === 200) {
                                this.$message.success('保存成功')
                                this.$emit('onlyGoBack')
                            }
                        })
                    } else {
                        courseEvaluationApi.updateStudentEva(this.teachForm).then(res => {
                            if (res.code === 200) {
                                this.$message.success('保存成功')
                                this.$emit('onlyGoBack')
                            }
                        })
                    }
                }
            })
        }
    },
    watch: {
    '$route'(to, from) {
      if (Object.values(to.query).length > 0) {
        this.routeParams = _.cloneDeep(to.query)
        if (this.routeParams.ifWithdraw === 'true' || this.routeParams.ifWithdraw === true) {
            this.ifDisabled = true
        }
        if (this.routeParams.managementId) {
            const param = {
                managementId: this.routeParams.managementId
            }
            courseEvaluationApi.getStudentEvaDetail(param).then(res => {
                if (res.code == 200) {
                    this.teachForm = res.data
                }
            })
        }
      }
    }
  }
}
</script>
